package com.thread.Concurrent;
//不安全的取钱
//两人去银行取钱、账户
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(10, "生活基金");
        Drawing my = new Drawing(account, 5, "我");
        Drawing myWife = new Drawing(account, 10, "老婆");
        my.start();
        myWife.start();

    }

    //账户
    static class Account {
        int money;//钱
        String purpose;//账户用途
        public Account(int money, String purpose) {
            this.money = money;
            this.purpose = purpose;
        }
    }

    //银行：模拟取款
    static class Drawing extends Thread {
        Account account;//账户
        int drawingMoney;//取出多少钱
        int nowMoney;//当前余额

        //构造方法
        public Drawing(Account account, int drawingMoney, String cardName) {
            super(cardName);//父类的有参构造，要写在方法的最前面
            this.account = account;
            this.drawingMoney = drawingMoney;
        }

        //重写run方法——>取钱
        @Override
        public void run() {
            //1、判断有没有钱
            if ((account.money - drawingMoney) < 0) {
                System.out.println("余额不足，无法操作！");
                return;
            }
            //模拟演示
            try {
                Thread.sleep(1000);//放大问题发生的可能性
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //卡内余额=卡内余额-取出的钱
            account.money = account.money - drawingMoney;
            //手里的钱
            nowMoney = nowMoney + drawingMoney;
            System.out.println(account.purpose+"余额为：" + account.money+"万");
            //Thread.currentThread().getName() = this.getName()
            System.out.println(this.getName() + "手里的钱：" + nowMoney+"万");
        }
    }
}
